# 使用Django的forms表单功能
import re
from django import forms
from book01 import models


class RegForm(forms.Form):
    """
    用户注册的表单
    """
    username = forms.CharField(label='用户名', max_length=30, min_length=3)
    email = forms.EmailField(label='邮箱')
    password = forms.CharField(label='密码', min_length=8,max_length=16,widget=forms.PasswordInput)
    password_again = forms.CharField(label='再次输入密码', min_length=8,max_length=16,widget=forms.PasswordInput)
    phone = forms.CharField(label='请输入手机号', min_length=11, max_length=11)

    def clean_username(self):
        username = self.cleaned_data['username']
        if models.Userinfo.objects.filter(username=username).exists():
            raise forms.ValidationError('用户名已存在')
        return username

    def clean_email(self):
        email = self.cleaned_data['email']
        if models.Userinfo.objects.filter(email=email).exists():
            raise forms.ValidationError('邮箱已存在')
        return email

    def clean_password_again(self):
        password = self.cleaned_data['password']
        password_again = self.cleaned_data['password_again']
        if password != password_again:
            raise forms.ValidationError('两次输入的密码不一致')
        return password

    # 验证手机号是否合法
    def clean_phone(self):
        phone = self.cleaned_data.get('phone')
        phone2 = r'^1[34578]\d{9}$'
        p = re.compile(phone2)
        if p.match(phone):
            return phone
        else:
            raise forms.ValidationError('手机号码非法')


class Author_Form(forms.Form):
    """
    作者表单功能，带验证 required=True 是默认的可以不写 error_messages错误提示的列表还无法展示
    """
    author = forms.CharField(label='作者姓名', max_length=50, )
    age = forms.CharField(label='年龄', max_length=3, )
    sex = forms.ChoiceField(label='性别', choices=((1, '男'), (2, '女')), )
    phone = forms.CharField(label='电话', min_length=11, max_length=11, )
    email = forms.EmailField(label='邮箱', )

    # 验证作者是否存在
    def clean_author(self):
        author = self.cleaned_data.get('author')
        if models.Author.objects.filter(author=author).exists():
            raise forms.ValidationError('作者姓名也存在')
        return author

    # 验证年龄是否合法
    def clean_age(self):
        age = self.cleaned_data.get('age')
        age2 = r'^\d{3}$'
        temp = re.compile(age2)
        if temp.match(age):
            return age
        else:
            raise forms.ValidationError('输入的年龄不合法')

    # 验证手机号是否合法
    def clean_phone(self):
        phone = self.cleaned_data.get('phone')
        phone2 = r'^1[34578]\d{9}$'
        p = re.compile(phone2)
        if p.match(phone):
            return phone
        else:
            raise forms.ValidationError('手机号码非法')


class Publisher_Form(forms.Form):
    """
    出版社表单功能，带验证
    """
    publisher = forms.CharField(label='出版社', max_length=50, )
    address = forms.CharField(label='地址', required=False, max_length=50)
    phone = forms.CharField(label='电话', min_length=11, max_length=11, )
    email = forms.EmailField(label='邮箱')

    # 验证作者是否存在
    def clean_publisher(self):
        publisher = self.cleaned_data.get('publisher')
        if models.Publisher.objects.filter(publisher=publisher).exists():
            raise forms.ValidationError('出版社已存在')
        return publisher

    # 验证手机号是否合法
    def clean_phone(self):
        phone = self.cleaned_data.get('phone')
        phone2 = r'^1[34578]\d{9}$'
        p = re.compile(phone2)
        if p.match(phone):
            return phone
        else:
            raise forms.ValidationError('手机号码非法')


class Book_Form(forms.Form):
    """
    书的表单
    """
    title = forms.CharField(label='书名', max_length=50, )
    date = forms.DateField(label='发行时间')
    author_info = models.Author.objects.all()
    author_choise = []
    for i in author_info:
        author_choise.append((i.id, i.author))
    author = forms.ChoiceField(label='作者', choices=tuple(author_choise))
    publisher_info = models.Publisher.objects.all()
    publisher_choise = []
    for i in publisher_info:
        publisher_choise.append((i.id, i.publisher))
    publisher = forms.ChoiceField(label='出版社', choices=tuple(publisher_choise))

    def clean_title(self):
        title = self.cleaned_data.get('title')
        if models.Book.objects.filter(title=title).exists():
            raise forms.ValidationError('书名已存在')
        return title
